package com.toocms.jinjuhang.ui.mine.order.details

import android.app.Application
import android.os.Bundle
import android.text.TextUtils
import androidx.core.graphics.drawable.DrawableCompat
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ResourceUtils
import com.blankj.utilcode.util.StringUtils
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.order_info.OrderDetailData
import com.toocms.jinjuhang.data.system.RefundButtonData
import com.toocms.jinjuhang.dialog.hint.HintDialog
import com.toocms.jinjuhang.dialog.order_cancel.OrderCancelDialog
import com.toocms.jinjuhang.ui.mine.order.OrderServiceItemModel
import com.toocms.jinjuhang.ui.mine.order.OrderStatus
import com.toocms.jinjuhang.ui.mine.order.logistics_details.LogisticsDetailsFgt
import com.toocms.jinjuhang.ui.mine.payment.PaymentFgt
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.jinjuhang.widget.view_model.showToast
import com.toocms.tab.base.BaseActivity
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger

class OrderDetailsModel(application: Application, val bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {

    val memberId by lazy {
        val currentMemberId = UserRepository.user.member_id
        bundle?.getString(Constants.BundleKey.KEY_MEMBER_ID, currentMemberId) ?: currentMemberId
    }
    val orderId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_ORDER_ID, "") ?: ""
    }
    val refundId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_REFUND_ID, "") ?: ""
    }

    val backObservableField by lazy {
        val content = ResourceUtils.getDrawable(R.mipmap.icon_arrow_left_black).mutate()
        DrawableCompat.setTint(content, 0xFFFFFFFF.toInt())
        ObservableField(content)
    }
    val backClickBindingCommand = BindingCommand<BindingAction>(this::finishFragment)

    val isApplyRefundObservableBoolean = ObservableBoolean(false)

    val dataObservableField = ObservableField<OrderDetailData>()
    val serviceItems = ObservableArrayList<OrderServiceItemModel>()
    val serviceItemBinding =
        ItemBinding.of<OrderServiceItemModel>(BR.orderServiceItemModel, R.layout.item_order_service)

    val isVisibleFunction0 = ObservableBoolean(false)
    val function0Hint = ObservableField<String>()

    val function0ClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val status = if (TextUtils.isEmpty(orderId)) OrderStatus.AFTER_SALE
        else OrderStatus.code2Status(
            dataObservableField.get()?.status?.toInt() ?: OrderStatus.ALL.code
        )
        when (status) {
            OrderStatus.AWAIT_PAYMENT -> { //TODO 支付
                val bundle = Bundle()
                bundle.putString(
                    Constants.BundleKey.KEY_ORDER_SN,
                    dataObservableField.get()?.order_sn
                )
                bundle.putString(
                    Constants.BundleKey.KEY_PAYMENT_SUM,
                    dataObservableField.get()?.pay_amounts ?: "00"
                )
                startFragment(PaymentFgt::class.java, bundle)
            }
            OrderStatus.AWAIT_RECEIVING -> { //TODO 确认收货
                HintDialog().apply {
                    content = StringUtils.getString(R.string.str_order_receiving_hint)
                    onPositiveClickListener = {
                        val params = mutableMapOf<String, String?>()
                        params["member_id"] = UserRepository.user.member_id
                        params["order_id"] = orderId
                        requestData(Urls.OrderInfo.SIGN_FOR,
                            params,
                            resultClass = String::class.java,
                            result = {
                                showToast(it)
                                Messenger.getDefault()
                                    .sendNoMsg(Constants.MessengerToken.TOKEN_REFRESH_ORDER)
                            })
                    }
                    show(
                        (ActivityUtils.getTopActivity() as BaseActivity).supportFragmentManager,
                        null
                    )
                }
            }
            else -> {}
        }


    })

    val isVisibleFunction1 = ObservableBoolean(false)
    val function1Selected = ObservableBoolean()
    val function1Hint = ObservableField<String>()

    val function1ClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val status = if (TextUtils.isEmpty(orderId)) OrderStatus.AFTER_SALE
        else OrderStatus.code2Status(
            dataObservableField.get()?.status?.toInt() ?: OrderStatus.ALL.code
        )
        when (status) {
            OrderStatus.AWAIT_PAYMENT -> { //TODO 取消订单
                cancelOrder(orderId)
            }
            OrderStatus.AWAIT_SHIPMENTS -> { //TODO 取消订单
                cancelOrder(orderId)
            }
            OrderStatus.AWAIT_RECEIVING, OrderStatus.AWAIT_EVALUATE -> { //TODO 查看物流
                val bundle = Bundle()
                bundle.putString(
                    Constants.BundleKey.KEY_LOGISTICS_NUMBER,
                    dataObservableField.get()?.logistics_number
                )
                startFragment(LogisticsDetailsFgt::class.java, bundle)
            }
            else -> {

            }
        }
    })


    init {
        initializeMessenger()
        requestData(true)
    }

    private fun initializeMessenger() {
        Messenger.getDefault().register(this, Constants.MessengerToken.TOKEN_REFRESH_ORDER) {
            requestData()
        }
    }

    private fun requestData(isShowLoading: Boolean = false) {
        val url: String
        val params = mutableMapOf<String, String?>()
        params["member_id"] = memberId
        if (orderId.isNotEmpty()) {
            //TODO 订单详情
            url = Urls.OrderInfo.ORDER_DETAIL
            params["order_id"] = orderId
        } else {
            //TODO 退款详情
            url = Urls.OrderInfo.REFUND_DETAIL
            params["refund_id"] = refundId
        }
        requestData(Urls.System.REFUND_BUTTON,
            resultClass = RefundButtonData::class.java,
            result = {
                isApplyRefundObservableBoolean.set("1" == it.status)
            },
            finish = {
                requestData(url,
                    params,
                    resultClass = OrderDetailData::class.java,
                    isShowLoading = isShowLoading,
                    result = {
                        dataObservableField.set(it)
                        isVisibleFunction0.set(false)
                        function0Hint.set("")
                        isVisibleFunction1.set(false)
                        function1Selected.set(false)
                        function1Hint.set("")
                        val status = if (TextUtils.isEmpty(orderId)) OrderStatus.AFTER_SALE
                        else OrderStatus.code2Status(
                            dataObservableField.get()?.status?.toInt() ?: OrderStatus.ALL.code
                        )
                        if (memberId == UserRepository.user.member_id) {
                            when (status) {
                                OrderStatus.AWAIT_PAYMENT -> {
                                    isVisibleFunction0.set(true)
                                    function0Hint.set(StringUtils.getString(R.string.str_payment))
                                    isVisibleFunction1.set(true)
                                    function1Selected.set(false)
                                    function1Hint.set(StringUtils.getString(R.string.str_cancel_order))
                                }
                                OrderStatus.AWAIT_SHIPMENTS -> {
                                    isVisibleFunction1.set(false)
                                    function1Selected.set(false)
                                    function1Hint.set(StringUtils.getString(R.string.str_cancel_order))
                                }
                                OrderStatus.AWAIT_RECEIVING -> {
                                    isVisibleFunction0.set(true)
                                    function0Hint.set(StringUtils.getString(R.string.str_confirm_receiving))
                                    isVisibleFunction1.set(true)
                                    function1Selected.set(true)
                                    function1Hint.set(StringUtils.getString(R.string.str_view_logistics))
                                }
                                OrderStatus.AWAIT_EVALUATE -> {
                                    isVisibleFunction1.set(true)
                                    function1Selected.set(true)
                                    function1Hint.set(StringUtils.getString(R.string.str_view_logistics))
                                }
                                OrderStatus.AFTER_SALE -> {

                                }
                                else -> {

                                }
                            }
                        }
                        serviceItems.clear()
                        it.goods_list?.forEach { commodityItem ->
                            commodityItem.order_id = orderId
                            serviceItems += OrderServiceItemModel(
                                this@OrderDetailsModel,
                                ObservableField(commodityItem),
                                ObservableField(status),
                                isApplyRefundObservableBoolean
                            )
                        }
                    })
            })
    }

    private fun cancelOrder(orderId: String?) {
        if (orderId.isNullOrEmpty()) return
        OrderCancelDialog().apply {
            this.type = Constants.Extra.REASON_TYPE_CANCELLATION_REASONS
            this.orderId = orderId
            onSucceedListener = {
                Messenger.getDefault().sendNoMsg(Constants.MessengerToken.TOKEN_REFRESH_ORDER)
            }
            show((ActivityUtils.getTopActivity() as BaseActivity).supportFragmentManager, null)
        }
    }
}